package com.yanchangapp.ui.activity.purchase;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.PsDetailProductAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.OrderDetailBean;
import com.yanchangapp.model.bean.OrderProductBean;
import com.yanchangapp.ui.presenter.OrderEnsureAtPresenter;
import com.yanchangapp.ui.view.OrderEnsureAtView;
import com.yanchangapp.widget.DelayShowDialog;
import com.yanchangapp.widget.SpannableMoney;
import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.NiceNestedScrollView;
import com.zxl.baselib.widget.TipDialog;
import com.zxl.baselib.widget.YCLoadingView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 订单确认页面数据...
 *
 * 传入orderID进行页面显示...
 *
 * 您的采购订单已提交至第三方物流平台审批
 */
public class POrderEnsureActivity extends BaseActivity<OrderEnsureAtView, OrderEnsureAtPresenter> implements OrderEnsureAtView {

    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ibAddMenu)
    ImageButton ibAddMenu;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.tvTextSingleName)
    TextView tvTextSingleName;
    @BindView(R.id.userHead)
    RelativeLayout userHead;
    @BindView(R.id.tvUserDept)
    TextView tvUserDept;
    @BindView(R.id.tvCreateTime)
    TextView tvCreateTime;
    @BindView(R.id.tvOrderNoTitle)
    TextView tvOrderNoTitle;
    @BindView(R.id.tvOrderNo)
    TextView tvOrderNo;
    @BindView(R.id.tvOrderContractTitle)
    TextView tvOrderContractTitle;
    @BindView(R.id.tvOrderContract)
    TextView tvOrderContract;
    @BindView(R.id.rlContract)
    RelativeLayout rlContract;
    @BindView(R.id.tvOrderCompanyTitle)
    TextView tvOrderCompanyTitle;
    @BindView(R.id.tvOrderCompany)
    TextView tvOrderCompany;
    @BindView(R.id.tvOrderAreaTitle)
    TextView tvOrderAreaTitle;
    @BindView(R.id.tvOrderArea)
    TextView tvOrderArea;
    @BindView(R.id.rvOrderDetail)
    RecyclerView rvOrderDetail;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    @BindView(R.id.scrollContent)
    NiceNestedScrollView scrollContent;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.btnApprove)
    Button btnApprove;
    @BindView(R.id.btnDrop)
    Button btnDrop;

    private static final String ORDER_ID = "order_id";
    private String orderId;

    private List<OrderProductBean> mOrderProductBeans = new ArrayList<>();
    private PsDetailProductAdapter mPsDetailProductAdapter;

    private DelayShowDialog mDelayShowDialog;

    private TipDialog mDropDialog,mBackDialog;

    public static void show(Activity activity, String orderID) {
        Intent intent = new Intent(activity, POrderEnsureActivity.class);
        intent.putExtra(ORDER_ID, orderID);
        activity.startActivity(intent);
    }

    @Override
    protected void init() {
        if (null != getIntent()) {
            orderId = getIntent().getStringExtra(ORDER_ID);
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_porder_ensure;
    }

    @Override
    protected OrderEnsureAtPresenter createPresenter() {
        return new OrderEnsureAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setLoadingState(LoadingType.LOADING);
        ivToolbarNavigation.setVisibility(View.INVISIBLE);
        tvToolbarTitle.setText("确认采购订单");
        ibAddMenu.setImageResource(R.mipmap.ic_toolbar_close);
        ibAddMenu.setVisibility(View.VISIBLE);
        initAdapter();
    }

    private void initAdapter() {
        // 设置商品的Adapter
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvOrderDetail.setHasFixedSize(true);
        rvOrderDetail.setNestedScrollingEnabled(false);
        rvOrderDetail.setLayoutManager(manager);
        rvOrderDetail.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this,0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mPsDetailProductAdapter = new PsDetailProductAdapter(R.layout.item_order_product_detail,mOrderProductBeans);
        rvOrderDetail.setAdapter(mPsDetailProductAdapter);
    }

    @Override
    protected void initData() {
        mPresenter.queryOrderDetail(orderId);
    }

    private void setLoadingState(LoadingType loadingType){
        switch (loadingType){
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE){
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:

                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.GONE){
                    scrollContent.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.GONE){
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }

    private void  showDelayDialog(){
        if (null == mDelayShowDialog){
            mDelayShowDialog = new DelayShowDialog(this);
        }
        mDelayShowDialog.show();
    }

    private void hideDelayDialog(){
        mDelayShowDialog.hide();
    }

    // 延迟2秒执行
    private void showSecondsBack(){
        showDelayDialog();
        UIUtils.postTaskDelay(new Runnable() {
            @Override
            public void run() {
                hideDelayDialog();
                reBackToListAndRefresh();
            }
        },2000);
    }

    private void release(){
        if (ycLoading.getVisibility() == View.VISIBLE){
            ycLoading.setVisibility(View.GONE);
        }
    }

    /**
     * 返回列表,并通知刷新
     */
    private void reBackToListAndRefresh(){
        mRxManager.post(POrderListActivity.REFRESH_LIST,true);
        reBackToList();
    }

    /**
     * 返回列表
     */
    private void reBackToList(){
        AppManager.getAppManager().returnToActivity(POrderListActivity.class);
    }

    @Override
    protected void initListener() {
        // 关闭弹窗,询问是否需要关闭
        ibAddMenu.setOnClickListener(v -> {
            showQuitDialog();
        });

        // 执行刷行
        btnNextRefresh.setOnClickListener(v -> {
            setLoadingState(LoadingType.LOADING);
            // 延迟1秒执行刷新
            UIUtils.postTaskDelay(new Runnable() {
                @Override
                public void run() {
                    mPresenter.queryOrderDetail(orderId);
                }
            },1000);
        });

        btnApprove.setOnClickListener(v -> mPresenter.submitOrderByID(orderId));

        btnDrop.setOnClickListener(v -> {
            showDropDialog();
        });
    }

    private void showDropDialog(){

        if (mDropDialog == null){
            mDropDialog = new TipDialog.Builder(this)
                    .setMessage("确定作废订单？")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            mPresenter.dropOrderByID(orderId);
                        }
                    })
                    .build();

        }
        mDropDialog.show();
    }

    private void showQuitDialog(){
        if (mBackDialog == null){
            mBackDialog = new TipDialog.Builder(this)
                    .setMessage("订单暂未提交,确定退出？")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            reBackToList();
                        }
                    }).build();
        }
        mBackDialog.show();
    }

    @Override
    protected void onDestroy() {
        release();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void getOrderDetailSuccess(OrderDetailBean orderDetailBean) {
        setLoadingState(LoadingType.SUCCESS);
        // 设置数据...
        // 设置人-部门
        tvUserDept.setText(ResHelper.getString(R.string.order_detail_name_dept,orderDetailBean.getBuyerName(),orderDetailBean.getDepartmentName()));
        // tag名
        tvTextSingleName.setText(orderDetailBean.getBuyerName().substring(0,1));
        // 创建时间
        tvCreateTime.setText(ResHelper.getString(R.string.order_detail_create_time, TimeUtil.getDayTime(orderDetailBean.getOrderDate())));
        // 单据编号
        tvOrderNo.setText(orderDetailBean.getOrderNo());
        // 供货单位
        tvOrderCompany.setText(orderDetailBean.getSupplierName());
        // 仓库
        tvOrderArea.setText(orderDetailBean.getAddress());

        String totalMoney = BigDecimalUtils.keep2Decimal(orderDetailBean.getTotalMoney());
        Log.e("金额", String.valueOf(orderDetailBean.getTotalMoney()));
        Log.e("金额", totalMoney);
        int len = totalMoney.length();
        SpannableString spannableString = new SpannableString(ResHelper.getString(R.string.down_order_sum,
                String.valueOf(orderDetailBean.getItemNum()),totalMoney));
        int totalLength = spannableString.length();
        spannableString.setSpan(new SpannableMoney(POrderEnsureActivity.this),
                totalLength-len-1,totalLength,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvProductSum.setText(spannableString);
        // 设置订单编号
        if (TextUtils.isEmpty(orderDetailBean.getContractId())){
            rlContract.setVisibility(View.GONE);
        }else {
            rlContract.setVisibility(View.VISIBLE);
            tvOrderContract.setText(orderDetailBean.getContractNo().toString());
        }

        if (orderDetailBean.getProducts() != null){
            mOrderProductBeans.clear();
            mOrderProductBeans.addAll(orderDetailBean.getProducts());
            mPsDetailProductAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void getOrderDetailFailure(String err) {
        setLoadingState(LoadingType.ERROR);
    }

    @Override
    public void dropOrderFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void dropOrderSuccess() {
        // 作废订单成功
        reBackToListAndRefresh();
    }



    @Override
    public void submitOrderFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void submitOrderSuccess() {
        // 作废订单成功
        showSecondsBack();
    }
}
